const mongoose = require('mongoose');

const translationSchema = new mongoose.Schema({
  // 词条键 (如: "nav.home")
  key: {
    type: String,
    required: true,
    index: true
  },
  
  // 命名空间 (如: "common", "product")
  namespace: {
    type: String,
    default: 'common',
    index: true
  },
  
  // 所属产品ID
  productId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Product',
    required: true,
    index: true
  },
  
  // 多语言值
  locales: {
    type: Map,
    of: String,
    required: true,
    default: new Map()
  },
  
  // 状态: draft | pending | approved | published
  status: {
    type: String,
    enum: ['draft', 'pending', 'approved', 'published'],
    default: 'draft',
    index: true
  },
  
  // 版本号
  version: {
    type: Number,
    default: 1
  },
  
  // 创建人
  createdBy: {
    type: String,
    required: true
  },
  
  // 审核人
  reviewer: {
    type: String,
    default: null
  },
  
  // 审核备注
  reviewNote: {
    type: String,
    default: null
  },
  
  // 是否已删除 (软删除)
  deleted: {
    type: Boolean,
    default: false,
    index: true
  }
}, {
  timestamps: true
});

// 复合索引：产品 + 命名空间 + 键，确保唯一性
translationSchema.index({ productId: 1, namespace: 1, key: 1, deleted: 1 }, { unique: true });

// 方法：更新状态
translationSchema.methods.updateStatus = function(newStatus, reviewer = null, note = null) {
  if (['pending', 'approved', 'published'].includes(newStatus)) {
    this.status = newStatus;
    if (reviewer) this.reviewer = reviewer;
    if (note) this.reviewNote = note;
    this.version += 1;
    return this.save();
  }
  throw new Error('无效的状态');
};

// 方法：添加/更新语言
translationSchema.methods.setLocale = function(locale, value) {
  this.locales.set(locale, value);
  // 如果是从 draft 创建，自动变为 pending
  if (this.status === 'draft' && this.locales.size > 0) {
    this.status = 'pending';
  }
  return this.save();
};

module.exports = mongoose.model('Translation', translationSchema);

